package com.sosee.cgfw.friends;

import android.app.Activity;
import android.content.ContentResolver;
import android.database.Cursor;
import android.graphics.Color;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.sosee.cgfw.R;
import com.sosee.cgfw.entity.ContactJson;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;
import com.sosee.cgfw.utils.Utils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.analytics.MobclickAgent;

import org.apache.http.entity.StringEntity;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Thinkpad on 2016/3/1.
 */
public class FriendsTel extends Activity implements AdapterView.OnItemClickListener {
    private HttpUtils httpUtils;
    private TelData telData;


    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }
    /**
     * 获取库Phon表字段
     **/
    private static final String[] PHONES_PROJECTION = new String[]{
            ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME, ContactsContract.CommonDataKinds.Phone.NUMBER,};

    /**
     * 联系人显示名称
     **/
    private static final int PHONES_DISPLAY_NAME_INDEX = 0;

    /**
     * 电话号码
     **/
    private static final int PHONES_NUMBER_INDEX = 1;

    /**
     * 头像ID
     **/
    private static final int PHONES_PHOTO_ID_INDEX = 2;

    /**
     * 联系人的ID
     **/
    private static final int PHONES_CONTACT_ID_INDEX = 3;


    /**
     * 联系人名称
     **/
    private ArrayList<String> mContactsName = new ArrayList<String>();
    /**
     * 联系人号码
     **/
    private ArrayList<String> mContactsNumber = new ArrayList<String>();
    private String phone = "18628031368";
    private ListView lv1;
    private ListView lv;


    String[] letter = {"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"};

    //放首字母的
    String[] nameLetter = {"A"};

    //放名称的
    String[] Name = {"长沙"};
    //吧首字母和名称放一起的。
    List<String> letterToCity = new ArrayList<String>();
    List cityName = new ArrayList<String>();
    List<FriendsListData.Data> datas;

    List<TelData> list = new ArrayList<TelData>();

    //    Map loctel= new HashMap();//以电话号码为键。
    List<FriendsTelData> loctel = new ArrayList<FriendsTelData>();
    List<FriendsTelData> reqtel = new ArrayList<FriendsTelData>();
    private String phone1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_friends_tel);
        httpUtils = new HttpUtils();

        getPhoneContacts();
//        request();
        request_get();
    }




    private void getPhoneContacts() {
        loctel.clear();
        ContentResolver resolver = this.getContentResolver();

        // 获取手机联系人
        Cursor phoneCursor = resolver.query(ContactsContract.CommonDataKinds.Phone.CONTENT_URI, PHONES_PROJECTION, null, null, null);


        if (phoneCursor != null) {
            while (phoneCursor.moveToNext()) {

                //得到手机号码
                String phoneNumber = phoneCursor.getString(PHONES_NUMBER_INDEX);

                //当手机号码为空的或者为空字段 跳过当前循环
                if (TextUtils.isEmpty(phoneNumber) || phoneNumber.length() != 11)
                    continue;

                //得到联系人名称
                String contactName = phoneCursor.getString(PHONES_DISPLAY_NAME_INDEX);

                //得到联系人ID
//                Long contactid = phoneCursor.getLong(PHONES_CONTACT_ID_INDEX);
                if(!mContactsName.contains(contactName)){
                    mContactsName.add(contactName);
                    mContactsNumber.add(phoneNumber);
                }




            }

            for (int i = 0; i < mContactsNumber.size(); i++) {
                FriendsTelData teldata1 = new FriendsTelData();
//                    System.out.println(mContactsNumber.get(i));
                phone = phone + "," + mContactsNumber.get(i);
                teldata1.setName(mContactsName.get(i));
                teldata1.setPhone(mContactsNumber.get(i));
                loctel.add(teldata1);

            }

            phoneCursor.close();
        }
    }







    private void init() {

        ImageButton friends_back2 = (ImageButton) findViewById(R.id.friends_back2);
        friends_back2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //获取电话名称的首字母和名字
        nameLetter = new String[mContactsName.size()];
        Name = new String[mContactsName.size()];
        for (int i = 0; i < mContactsName.size(); i++) {

            String name = mContactsName.get(i);
            //获取名称
            Name[i] = name;
            //获取名称首字母
            nameLetter[i] = Utils.getPinYinHeadChar(name);
            //吧名称和首字母以键值对存起来。
        }


        initView();
    }
    //上传通讯录信息 并根据服务器返回数据 判断是否可加为好友
    private void request() {
        //?cot&userID
        reqtel.clear();
        ContactJson json=new ContactJson();
        json.setPhone(phone);
        json.setUserid(Constans.userID);
        RequestParams params=new RequestParams();
        String jso=com.alibaba.fastjson.JSONObject.toJSONString(json);
        try {
            params.setContentType("application/json");
            params.setBodyEntity(new StringEntity(jso,"UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        LogUtils.log_E("测试json转换：" + jso);
//        params.addBodyParameter("android", jso);
        //默认url： Constans.userID + "&phone=" + phone

        httpUtils.send(HttpRequest.HttpMethod.POST, Constans.GETTEL_URL, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String s = responseInfo.result;
                LogUtils.log_E("测试服务器返回数据：" + responseInfo.result);
                FriendsTelData teldata = new FriendsTelData();
                try {
                    JSONObject json = new JSONObject(s);

                    if ("success".equals(json.getString("status"))) {

                        JSONArray data = json.getJSONArray("data");
                        int y = 0;
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject jsonObject = data.getJSONObject(i);
                            String flag = jsonObject.getString("flag");
                            if ("1".equals(flag) || "2".equals(flag)) {
                                JSONObject userInfo = jsonObject.getJSONObject("userInfo");
                                teldata.setPhone(userInfo.getString("phone"));
                                teldata.setNickname(userInfo.getString("nickname"));
                                teldata.setID(userInfo.getString("ID"));
                                teldata.setFlag(jsonObject.getString("flag"));
                                reqtel.add(teldata);

                            }
                        }

                        init();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络获取异常通讯录");
            }
        });


    }

    //get方式提交数据
    private void request_get() {
        //?cot&userID
        reqtel.clear();
        httpUtils.send(HttpRequest.HttpMethod.GET, Constans.GETTEL_URL+"&userID="+Constans.userID+"&phone="+phone,new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> responseInfo) {
                String s = responseInfo.result;
                LogUtils.log_E("测试服务器返回数据："+responseInfo.result);
                FriendsTelData teldata = new FriendsTelData();
                try {
                    JSONObject json = new JSONObject(s);

                    if ("success".equals(json.getString("status"))) {

                        JSONArray data = json.getJSONArray("data");
                        int y = 0;
                        for (int i = 0; i < data.length(); i++) {
                            JSONObject jsonObject = data.getJSONObject(i);
                            String flag = jsonObject.getString("flag");
                            if ("1".equals(flag) || "2".equals(flag)) {
                                JSONObject userInfo = jsonObject.getJSONObject("userInfo");
                                teldata.setPhone(userInfo.getString("phone"));
                                teldata.setNickname(userInfo.getString("nickname"));
                                teldata.setID(userInfo.getString("ID"));
                                teldata.setFlag(jsonObject.getString("flag"));
                                reqtel.add(teldata);

                            }
                        }

                        init();

                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }


            }

            @Override
            public void onFailure(HttpException e, String s) {
                Utils.showToast("网络获取异常通讯录");
            }
        });


    }

    private void initView() {
        //吧字母和名字合并。

        String str = "";
        for (int i = 0; i < letter.length; i++) {
            str = letter[i];
            boolean isAddLetter = false;
            for (int j = 0; j < nameLetter.length; j++) {
                if (str.equals(nameLetter[j])) {
                    if (!isAddLetter) {
                        letterToCity.add(str);
                        isAddLetter = true;
                    }
                    letterToCity.add(Name[j]);
                }
            }
        }

        for (int n = 0; n < letterToCity.size(); n++) {
        }

        lv = (ListView) findViewById(R.id.friends_telbook);
        lv.setAdapter(new MyAdapter());

        lv1 = (ListView) findViewById(R.id.friends_letter);
        lv1.setAdapter(new MyAdapter1());
        lv1.setOnItemClickListener(this);


    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        switch (parent.getId()) {
            case R.id.friends_letter:
                for (int i = 0; i < letterToCity.size(); i++) {
                    if (letter[position].equals(letterToCity.get(i))) {
                        lv.setSelection(i);
                        break;
                    }
                }
                break;

            default:
                break;
        }
    }

    //这是显示旁边abc的右导航边框。
    class MyAdapter1 extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return letter == null ? 0 : letter.length;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return letter[position];
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = LayoutInflater.from(FriendsTel.this).inflate(R.layout.letter_list, null);
            TextView tv = (TextView) view.findViewById(R.id.letterListTextView);
            tv.setText(letter[position]);
            return view;
        }

    }


    //复杂listview
    class MyAdapter extends BaseAdapter {

        final static int TYPE_1 = 1;

        final static int TYPE_2 = 2;

        @Override
        public int getCount() {
            // TODO Auto-generated method stub

            return letterToCity == null ? 0 : letterToCity.size();

        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return letterToCity.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public int getItemViewType(int position) {

            //这里是来判断条目类型的
            for (int i = 0; i < letter.length; i++) {
                if (letterToCity.get(position).equals(letter[i])) {
                    return TYPE_1;
                }
            }
            return TYPE_2;

        }

        @Override
        public int getViewTypeCount() {
            return 3;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            /**
             * 即使convertView缓存了一些布局，但是在重构时，根本不知道怎么样去让convertView返回你所需要的布局，这时你需
             * 要让adapter知道我当前有哪些布局，我重构Item时的布局选取规则，好让convertView能返回你需要的布局。
             * 需要重写以下两个函数
             * @Override
             * public int getItemViewType(int position) {}这个函数获取在getView中创建的视图的类型
             * @Override
             * public int getViewTypeCount() {}返回在getView中创建视图类型的数量
             * 至于这两个方法的详细用处，自己看api即可
             */
            ViewHolder1 vh1 = null;
            ViewHolder2 vh2 = null;
            //获取条目对象类型。
            int type = getItemViewType(position);
            if (convertView == null) {
                switch (type) {
                    case TYPE_1:
                        convertView = LayoutInflater.from(FriendsTel.this).inflate(R.layout.letter, null);
                        vh1 = new ViewHolder1();
                        vh1.tv = (TextView) convertView.findViewById(R.id.letterTextView);
                        convertView.setTag(vh1);
                        break;
                    case TYPE_2:

                        convertView = LayoutInflater.from(FriendsTel.this).inflate(R.layout.friends_listfriends_item, null);
                        vh2 = new ViewHolder2();
                        vh2.friends_telname = (TextView) convertView.findViewById(R.id.friends_telname);
                        vh2.friends_appstuta = (TextView) convertView.findViewById(R.id.friends_appstuta);
                        vh2.friends_addstutass = (TextView) convertView.findViewById(R.id.friends_addstutass);


                        convertView.setTag(vh2);
                        break;
                    default:
                        break;
                }
            } else {
                switch (type) {
                    case TYPE_1:
                        vh1 = (ViewHolder1) convertView.getTag();
                        break;
                    case TYPE_2:
                        vh2 = (ViewHolder2) convertView.getTag();
                        break;
                    default:
                        break;
                }
            }
            //这里就是设置每个条目需要显示的值。
            switch (type) {
                case TYPE_1:
                    vh1.tv.setText(letterToCity.get(position));
                    vh1.tv.setTextColor(Color.WHITE);
                    break;
                case TYPE_2:
                    String name =letterToCity.get(position);

                    //遍历本地数据判断
                    String phone_test="";
                    for (int i = 0; i < loctel.size(); i++) {
//                              letterToCity是所有数据集合，如果设置的这个条目和本地的一个条目相等。
                        if (name.equals(loctel.get(i).getName())) {
                            phone_test = loctel.get(i).getPhone();
                            LogUtils.log_E("适配器：" + phone_test + name);
                            break;
                            //然后我们要拿到这个条目对应的电话号码。
//                                    loctel.get(i).getPhone()这就是电话号码。拿去请求回来的数组遍历循环。
                            //我们就要拿到这个名字对应的号码去遍历网络请求的回来的list看有没有相同电话，
                        }
                    }
                    vh2.friends_telname.setText(name);
                    vh2.friends_appstuta.setText("未使用app");
                    vh2.friends_addstutass.setText("");
                    LogUtils.log_E("测试之前："+phone_test);
                    test(vh2, phone_test,name);
                    break;
                default:
                    break;
            }
            return convertView;

        }
    }



    public void test(ViewHolder2 vh2,String phon,String name){
       String realname= vh2.friends_telname.getText().toString();
        for (int j = 0; j < reqtel.size(); j++) {
            //如果有相同号码。判断flag
            if (phon.equals(reqtel.get(j).getPhone())&&name.equals(realname)) {
                LogUtils.log_E("测试比较："+phon+":::"+name+"realname:"+realname);

                if ("1".equals(reqtel.get(j).getFlag())||"0".equals(reqtel.get(j).getFlag())||"-1".equals(reqtel.get(j).getFlag())) {
                    vh2.friends_appstuta.setText(reqtel.get(j).getNickname());
                    String text="";
                    if("1".equals(reqtel.get(j).getFlag())){
                        text="已添加";
                    }else if("-1".equals(reqtel.get(j).getFlag())){
                        text="等待通过";
                    }else{
                        text="拒绝";
                    }
                    vh2.friends_addstutass.setText(text);
                    break;
                } else if ("2".equals(reqtel.get(j).getFlag())) {
                    LogUtils.log_E("测试通讯录好友 加为好友："+phon+"网络号码："+reqtel.get(j).getPhone());
                    vh2.friends_appstuta.setText(reqtel.get(j).getNickname());
                    vh2.friends_addstutass.setText("加为好友");
                    final ViewHolder2 finalVh = vh2;
                    final String id = reqtel.get(j).getID();
                    vh2.friends_addstutass.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if ("加为好友".equals(finalVh.friends_addstutass.getText().toString())) {

                                //这里请求网络
                                httpUtils.send(HttpRequest.HttpMethod.GET, Constans.ADDFRIENDS_URL + Constans.userID + "&friendsID=" + id, new RequestCallBack<String>() {
                                    @Override
                                    public void onSuccess(ResponseInfo<String> responseInfo) {
                                        String s = responseInfo.result;
                                        System.out.println("这是返回的值" + s);
                                        //发送消息到主线程通知更改  加为好友为等待验证。
                                        finalVh.friends_addstutass.setText("等待验证");
                                        Utils.showToast("请求已经发送");


//
                                    }

                                    @Override
                                    public void onFailure(HttpException e, String s) {

                                        Utils.showToast("网络获取异常");
                                    }
                                });


                            }
                        }
                    });

                    break;
                } else {
                    break;
                }

            } else {
                break;
            }

        }
    }
}







class ViewHolder1 {
    TextView tv;
}
class ViewHolder2 {
    TextView friends_telname;
    TextView friends_appstuta;
    TextView friends_addstutass;

}

